package com.yauchu.kegra.graph.traversers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.jgrapht.DirectedGraph;

import com.yauchu.kegra.graph.GraphNode;
import com.yauchu.kegra.graph.NumberedEdge;

public abstract class GraphNodeTraverser<V> {

	
	DirectedGraph<GraphNode, NumberedEdge> graph;
	
	public GraphNodeTraverser(DirectedGraph<GraphNode, NumberedEdge> graph)
	{
		this.graph=graph;
		
	}
	

	protected abstract V reduce(GraphNode current_node,ArrayList<V> res);

	

	protected V reduceInOrderDownToDepth(GraphNode root, int depth) {
		ArrayList<V> results = new ArrayList<V>();
		if (depth != 0) {
			
			
			Set<NumberedEdge> edgeset = graph.outgoingEdgesOf(root);

			List<NumberedEdge> edgelist = new ArrayList(edgeset);

			//Comparator comparator= Collections.reverseOrder();
			
			Collections.sort(edgelist);

			Iterator<NumberedEdge> iteredge = edgelist.iterator();

			List<GraphNode> lgr = new ArrayList<GraphNode>();

			NumberedEdge currentedge;

			while (iteredge.hasNext()) {
				currentedge = iteredge.next();

				GraphNode what = currentedge.getV2();
				lgr.add(what);
				
			}
			Iterator<GraphNode> iternode = lgr.iterator();

			// LinearLayout newLayout= new LinearLayout(mainView.getContext());
			// newLayout.setOrientation(LinearLayout.HORIZONTAL);
			// mainView.addView(newLayout);

			while (iternode.hasNext()) {
				
				V temp=reduceInOrderDownToDepth(iternode.next(),depth - 1);
				 if (temp!=null){
					 results.add(temp);
					 
				 }
				 

			}
			

		}
		return this.reduce(root,results);
		
	}

}
